<script lang="ts" setup>
import { computed, nextTick, onMounted, ref, watch } from 'vue';
import { useVbenVxeGrid } from '#/adapter/vxe-table';

const props = defineProps<{
  items?: any[];
}>();

const emit = defineEmits<{
  (e: 'update:items', value: any[]): void;
  (e: 'remove', id: number): void;
  (e: 'total', value: number): void;
}>();

// 内部数据源
const rowsRef = ref<any[]>([]);

const totalAmount = computed(() => {
  return (rowsRef.value || []).reduce((sum, row: any) => sum + ((row?.goodsSku?.price || 0) * (row?.quantity || 0)), 0);
});

const [Grid, gridApi] = useVbenVxeGrid({
  // formOptions: {
  //   schema: [],
  // },
  gridOptions: {
    minHeight: 300,
    columns: [
      { field: 'goods_name', title: '名称', minWidth: 160, showOverflow: true },
      { field: 'price', title: '单价', width: 100, align: 'right', headerAlign: 'right', slots: { default: 'price' } },
      { field: 'quantity', title: '数量', width: 120, align: 'center', headerAlign: 'center', slots: { default: 'quantity' } },
      { field: 'subtotal', title: '小计', width: 120, align: 'right', headerAlign: 'right', slots: { default: 'subtotal' } },
      { title: '操作', width: 100, fixed: 'right', align: 'center', headerAlign: 'center', slots: { default: 'actions' } },
    ],
    data: [],
    toolbarConfig: {
      search: false,
      refresh: false,
    },
    rowConfig: { keyField: 'goods_id', isHover: true },
  },
});

async function syncData() {
  await nextTick();
  const rows = (rowsRef.value || []).map((r: any) => ({
    ...r,
    price: r?.goodsSku?.price || 0,
  }));
  await (gridApi as any).grid.reloadData(rows);
  emit('total', totalAmount.value);
}

onMounted(async () => {
  // 初始同步 props.items
  if (Array.isArray(props.items)) {
    rowsRef.value = props.items.map((r: any) => ({ ...r }));
  }
  await syncData();
});

watch(
  () => props.items,
  () => {
    if (Array.isArray(props.items)) {
      rowsRef.value = props.items.map((r: any) => ({ ...r }));
    }
    syncData();
  },
  { immediate: true, deep: true },
);

function onQuantityChange(row: any) {
  const list = [...(props.items || [])];
  const idx = list.findIndex((x: any) => x.goods_id === row.goods_id);
  if (idx !== -1) {
    list[idx] = { ...list[idx], quantity: row.quantity };
    emit('update:items', list);
  }
  // 同步内部数据
  const i = rowsRef.value.findIndex((x: any) => x.goods_id === row.goods_id);
  if (i !== -1) rowsRef.value[i].quantity = row.quantity;
  syncData();
}

function onRemove(row: any) {
  emit('remove', row.goods_id);
  rowsRef.value = rowsRef.value.filter((r) => r.goods_id !== row.goods_id);
  syncData();
}

function addItem(item: any) {
  if (!item) return;
  const idx = rowsRef.value.findIndex((x: any) => x.goods_id === item.goods_id);
  if (idx !== -1) {
    const stock = Number(item?.stock ?? rowsRef.value[idx]?.stock ?? 0);
    const nextQty = Number(rowsRef.value[idx].quantity || 0) + 1;
    rowsRef.value[idx].quantity = stock > 0 ? Math.min(nextQty, stock) : nextQty;
  } else {
    rowsRef.value.push({ ...item, quantity: 1 });
  }
  syncData();
}

function setItems(items: any[]) {
  rowsRef.value = Array.isArray(items) ? items.map((r) => ({ ...r })) : [];
  syncData();
}

function clear() {
  rowsRef.value = [];
  syncData();
}

function getItems() {
  return rowsRef.value.map((r) => ({ ...r }));
}

defineExpose({ gridApi, totalAmount, addItem, setItems, clear, getItems });
</script>

<template>
  <Grid>
    <template #price="{ row }">¥{{ Number(row?.price || 0).toFixed(2) }}</template>
    <template #quantity="{ row }">
      <a-input-number v-model:value="row.quantity" :min="1" :max="row.stock" size="small" style="width: 80px" @change="onQuantityChange(row)" />
    </template>
    <template #subtotal="{ row }">¥{{ ((row?.price || 0) * (row?.quantity || 0)).toFixed(2) }}</template>
    <template #actions="{ row }">
      <a-button type="link" danger size="small" @click="onRemove(row)">删除</a-button>
    </template>
  </Grid>
</template>

<style scoped>
</style>


